//
//  SimpleWebViewController.m
//  QQMiniAppSDK
//
//  Created by Goyoung on 2020/4/13.
//

#import "SimpleWebViewController.h"

@interface SimpleWebViewController ()

@property (nonatomic, strong) NSURLRequest *request;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, assign) BOOL original_translucent;
@property (nonatomic, assign) BOOL isLastEnabledInteractivePopGesture;

@end

@implementation SimpleWebViewController

- (instancetype)initWithURL:(NSURL *)url {
    return [self initWithRequest:[NSURLRequest requestWithURL:url] configuration:nil];
}

- (instancetype)initWithRequest:(NSURLRequest *)request configuration:(WKWebViewConfiguration *)config {
    if (self = [super init]) {
        self.request = request;

        if(!config) {
            config = [WKWebViewConfiguration new];
        }
        self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.extendedLayoutIncludesOpaqueBars = YES;
    [self.view addSubview:self.webView];
    [self.webView loadRequest:self.request];
    
    if(self.forcePortrait) {
        NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
        [UIViewController attemptRotationToDeviceOrientation];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    if (self.navigationController.navigationBar.translucent) {
        self.original_translucent = self.navigationController.navigationBar.translucent;
        self.navigationController.navigationBar.translucent = NO;
    }
    
    [self setNavigationBar];
}

- (void)viewDidLayoutSubviews {
    CGRect frame = self.view.bounds;
    frame.origin.y = self.navigationController.navigationBar.frame.size.height + [[UIApplication sharedApplication] statusBarFrame].size.height;
    frame.size.height = frame.size.height - frame.origin.y;
    self.webView.frame = frame;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.original_translucent) {
        self.navigationController.navigationBar.translucent = YES;
    }
    
    if (self.disableInteractivePopGestureRecognizer) {
        self.navigationController.interactivePopGestureRecognizer.enabled = self.isLastEnabledInteractivePopGesture;
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.disableInteractivePopGestureRecognizer) {
        UIGestureRecognizer *recognizer = self.navigationController.interactivePopGestureRecognizer;
        self.isLastEnabledInteractivePopGesture = recognizer.isEnabled;
        recognizer.enabled = NO;
    }
}


- (void)setNavigationBar {
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(leftBarBtnClicked)];
    self.navigationItem.leftBarButtonItem = backItem;
    self.navigationController.navigationBar.tintColor = UIColor.blackColor;
    [self setNavBackgroundColor:self.navigationController.navigationBar color:[UIColor whiteColor]];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)setNavBackgroundColor:(UINavigationBar *)navigationBar color:(UIColor *)color {
    if (@available(iOS 15.0, *)) {
        UINavigationBarAppearance *appearance = [[UINavigationBarAppearance alloc] init];
        [appearance configureWithTransparentBackground];
        appearance.backgroundImage = nil;
        appearance.backgroundColor = color;
        navigationBar.standardAppearance = appearance;
        navigationBar.scrollEdgeAppearance = appearance;
    } else {
        self.navigationController.navigationBar.translucent = NO;
        UIImage *image = [navigationBar backgroundImageForBarMetrics:UIBarMetricsDefault];
        if (image) {
            [navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
        }
        [navigationBar setShadowImage:[UIImage new]];
        [navigationBar setBarTintColor:color];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"title"] && object == self.webView) {
        self.title = self.webView.title;
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    // 设置状态栏，白底黑字
    return UIStatusBarStyleDefault;
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"title"];
}

- (void)leftBarBtnClicked {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if(self.forcePortrait) {
        return UIInterfaceOrientationMaskPortrait;
    }
    return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscape;
}


@end
